package com.woniuxy.auth.controller;

import com.woniuxy.entity.ResponseResult;
import com.woniuxy.entity.User;
import com.woniuxy.util.JwtUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 作者
 * @create 2025-07-02 11:03
 */
@RestController
@RequestMapping("/auth")
public class AuthController {


    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    @RequestMapping("/login")
    public ResponseResult<String> login(@RequestBody User user, HttpServletResponse response) {
        //查询用户名，密码判断是否正确
        if ("a".equals(user.getUname()) && "aaa".equals(user.getPwd())) {
            //登录成功,生成token，添加到请求头，响应给前端，id就是角色id
            String token = JwtUtil.create("1",user.getUname());
            //token存入redis
            redisTemplate.opsForValue().set("token:"+token,"a",60, TimeUnit.SECONDS);
            //登录成功以后，查询当前用户角色的权限，存到redis中
            List<String> permissions=new ArrayList<>();
            permissions.add("GET:/student");
            permissions.add("POST:/student");
            redisTemplate.opsForValue().set("role:"+1,permissions);
//            String fresh = JwtUtil.createRefresh("1",user.getUname());
            response.setHeader("token",token);
//            response.setHeader("fresh",fresh);
            //前后分离程序，必须暴露响应头，否则无法获取响应头
//            response.setHeader("Access-Control-Expose-Headers","token,fresh");
            response.setHeader("Access-Control-Expose-Headers","*");
            return new ResponseResult<>(200,"success","登录成功");
        }
         return new ResponseResult<>(401,"error","登录失败");
    }

}
